package com.rchat.pocmini.common.update;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.widget.TextView;

import com.aso.common.dialog.CustomDialog;
import com.aso.common.dialog.LoadingDialog;
import com.aso.common.global.CommonGlobal;
import com.aso.common.http.bean.BaseBean;
import com.aso.common.http.delegate.HttpCallbackImpl;
import com.aso.common.http.utils.HttpUtils;
import com.aso.common.http.utils.NetErrCode;
import com.aso.common.utils.AppUtils;
import com.aso.common.utils.FileUtils;
import com.aso.common.utils.MD5Utils;
import com.aso.common.utils.ToastUtils;
import com.aso.common.utils.Utils;
import com.itsdf07.alog.ALog;
import com.rchat.pocmini.R;
import com.rchat.pocmini.bean.AppInfo;
import com.rchat.pocmini.bean.AppUpdateBean;
import com.rchat.pocmini.global.AppGlobal;
import com.rchat.pocmini.global.HttpCodeGlobal;
import com.rchat.pocmini.global.RequestParam;
import com.rchat.pocmini.global.UrlsGlobal;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * @Description ：版本更新管理器
 * @Author itsdf07
 * @Time 2017/10/13
 */

public class AppUpdateManager {
    private static AppUpdateManager mInstance;
    private Context mContext;
    private IDownLoadCallback mDownLoadCallback;

    private boolean isDownLoading = false;

    private Call mCall;

    public LoadingDialog mLoadingDialog;

    /**
     * 下载器相关回调接口
     */
    public interface IDownLoadCallback {
        /**
         * 下载进度
         *
         * @param progress
         */
        void onProgress(long progress);

        /**
         * 文件下载完成
         *
         * @param file
         */
        void onDownLoadFinish(File file);

    }

    public static AppUpdateManager getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new AppUpdateManager();
        }
        mInstance.mContext = context;
        return mInstance;
    }

    public void destory() {
        if (mDownLoadCallback != null) {
            mDownLoadCallback = null;
        }
        if (mInstance != null) {
            mInstance = null;
        }
    }

    public boolean isDownLoading() {
        return isDownLoading;
    }

    public void setDownLoading(boolean downLoading) {
        isDownLoading = downLoading;
    }

    /**
     * 设置下载相关回调
     *
     * @param callback
     */
    public void setDownLoadCallback(IDownLoadCallback callback) {
        ALog.dTag("callback", "callback = %s", callback);
        mDownLoadCallback = callback;
        mContext = null;
    }

    AppInfo mAppInfo;

    public void setAppinfo(AppInfo info) {
        mAppInfo = info;
    }

    /**
     * 检测版本更新
     *
     * @param model
     * @see AppUpdateGlobal.CheckUpdateModel
     */
    public void checkUpdate(final String model) {
        Map<String, String> param = new HashMap<>();
        String body;
        param.put("channel", AppUtils.getRchatChannelCode());
        if (AppUpdateGlobal.CheckUpdateModel.PLUGIN.equals(model)) {
            param.put("status", "1");
            if (mAppInfo != null) {
                param.put("versionName", mAppInfo.getVersionName());
                param.put("versionCode", mAppInfo.getVersionCode() + "");
                setAppinfo(null);
            } else {
                param.put("versionName", "0.1");
                param.put("versionCode", "1");
            }
            //body = {"code":1001,"data":{"platform":1,"version":"1.0","enterprise":1,"versionCode":"2","versionName":"1.1","status":"1"}}
            body = RequestParam.requestRootParam(HttpCodeGlobal.REQ_CODE_1001, param);
        } else {
            param.put("branch", AppGlobal.APPTYPE);
            param.put("versionName", AppUtils.getVersionName(Utils.getApplication()));
            param.put("versionCode", AppUtils.getVersionCode(Utils.getApplication()) + "");
            //body = {"code":1001,"data":{"platform":1,"version":"1.0","enterprise":1,"versionCode":"14","versionName":"1.1.27.2171013","branch":"1"}}
            body = RequestParam.requestRootParam(HttpCodeGlobal.REQ_CODE_1001, param);
        }

        HttpUtils.postAsyn(UrlsGlobal.getUrl(UrlsGlobal.CHECK_UPDATE), body, new HttpCallbackImpl<AppUpdateBean>() {
            @Override
            public void onStart() {
                if (AppUpdateGlobal.CheckUpdateModel.CHECK.equals(model)) {
                    showLoading("版本更新检测中，请稍候！");
                }
            }

            @Override
            public void onSuccess(AppUpdateBean bean) {
                if (TextUtils.isEmpty(bean.getData().getPath())) {
                    if (AppUpdateGlobal.CheckUpdateModel.CHECK.equals(model)) {
                        bean.setDesc("已经是最新版本");
                        onFailureResult(bean);
                        onFinish();
                    }
                    return;
                }
                checkNewVersion(bean);
            }

            @Override
            public void onFailureResult(BaseBean bean) {
                ToastUtils.showToast(bean.getDesc());
            }

            @Override
            public void onFinish() {
                dismissLoading();
            }
        });

    }

    /**
     * 开始下载
     */
    public void onStartDownLoad(final AppUpdateBean bean) {
        String apkFileDwonLoadUrl = bean.getData().getPath();//apk文件下载地址
        String apkFileSavePath = getApkFileRootPath();//下载的apk文件存储路径
        String apkFileName = getApkFileName(bean.getData().getVersionName());//下载apk文件的名称

        File apkFile = new File(apkFileSavePath + apkFileName);
        boolean fileIsExites = FileUtils.isFileExists(apkFile);
        /**
         *1、文件存在，且MD5校验成功后，认可该文件与服务器对应的新版本是同一个文件时，则不在重新下载
         * 防止曾经下载过该版本后没有执行安装，并且用户手动改过该文件
         */
        if (fileIsExites
                && checkApkMD5(bean.getData().getMd5(), apkFile)) {
            openApk(Utils.getApplication(), apkFile);
            return;
        }
        delOtherApkFile(apkFile, apkFileSavePath);
        mCall = AppDownLoader.getInstance().startDownLoad(apkFileDwonLoadUrl, apkFileSavePath, apkFileName, new AppDownLoader.IDownLoaderCallback() {
            @Override
            public void onStartDownLoader() {
                isDownLoading = true;
                ToastUtils.showToast("开始下载");
            }

            @Override
            public void onDownLoading(long currentTotalLen, long totalLen) {
                if (mDownLoadCallback != null) {
                    currentTotalLen = (currentTotalLen * 100) / totalLen;
                    mDownLoadCallback.onProgress(currentTotalLen);
                }
            }

            @Override
            public void onFinishDownLoaded(File file) {
                isDownLoading = false;
                ALog.dTag("downloadCall", "mCall.isCanceled = %s", mCall.isCanceled());
                if (mCall != null && !mCall.isCanceled()) {
                    boolean isMD5Success = checkApkMD5(bean.getData().getMd5(), file);
                    if (!isMD5Success) {
                        onErrorDownLoaded(NetErrCode.ERR_FAILURE_RESPONSE_MD5, mContext.getString(R.string.tip_result_code_md5_error));
                    }
                }

                if (mDownLoadCallback != null) {
                    mDownLoadCallback.onDownLoadFinish(file);
                }
//                delOtherApkFile(file, getApkFileRootPath());
            }

            @Override
            public void onErrorDownLoaded(String errCode, String err) {
                isDownLoading = false;
                if (NetErrCode.ERR_FAILURE_RESPONSE_CANCLE.equals(errCode)) {
                    return;
                }
                ToastUtils.showToast(err);
            }
        });
    }

    /**
     * 取消下载
     */
    public void onCancleDownLoad() {
        if (mCall != null) {
            mCall.cancel();
        }
    }

    /**
     * 暂停下载
     */
    public void onPauseDownLoad() {

    }

    /**
     * 继续下载
     */
    public void onContinueDownLoad() {

    }

    /**
     * 校验MD5
     *
     * @param md5
     * @param file
     * @return
     */
    public boolean checkApkMD5(String md5, File file) {
        if (!FileUtils.isFileExists(file) || TextUtils.isEmpty(md5)) {
            return false;
        }
        String fileMD5 = MD5Utils.getFileMD5(file);
        if (null == fileMD5) {
            return false;
        }
        if (md5.equalsIgnoreCase(fileMD5)) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * @return 下载的Apk文件根目录/rchat/apk/
     */
    public String getApkFileRootPath() {
        return FileUtils.getInnerSDPath(Utils.getApplication()) + CommonGlobal.BASE_PATH + AppGlobal.BASE_PATH_APK;
    }

    /**
     * 拼接下载的文件名称
     *
     * @param version
     * @return
     */
    public String getApkFileName(String version) {
        return "v" + version + "_release_rchat.apk";
    }


    /**
     * 自动安装apk文件
     *
     * @param context
     * @param file
     */
    public void openApk(Context context, File file) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        context.startActivity(intent);
    }


    /**
     * 删除指定文件外的文件
     *
     * @param result           不删除的文件
     * @param saveFileRootPath 删除文件的根目录
     */
    private void delOtherApkFile(File result, String saveFileRootPath) {
        File[] listFiles = FileUtils.getFileList(saveFileRootPath);
        //如果路径不存在，则获取的listFiles为null
        if (listFiles == null) {
            return;
        }
        List<File> delFileList = new ArrayList<>();
        for (File delFile : listFiles) {
            if (delFile == null) {
                continue;
            }
            if (result == null) {
                continue;
            }
            if (result.getName().equals(delFile.getName())) {
                continue;
            }
            delFileList.add(delFile);
        }
        FileUtils.delJunkFile(delFileList, true, null);
    }

    /**
     * 检测到新版本
     */
    private void checkNewVersion(final AppUpdateBean bean) {
        CustomDialog.Builder builder = new CustomDialog.Builder(mContext);
//        final ClearEditText view = (ClearEditText) LayoutInflater.from(mContext).inflate(R.layout.layout_modify_nickname, null);
        TextView content = new TextView(mContext);
        content.setText(bean.getData().getDescX());
        builder.setContentView(content);
        builder.setTitle("版本信息");
        builder.setPositiveButton(mContext.getString(R.string.confirm), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                onStartDownLoad(bean);
            }
        });

        builder.setNegativeButton(mContext.getString(R.string.cancle),
                new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });

        builder.create().show();
    }

    /**
     * 加载对话框
     *
     * @param content
     */
    public void showLoading(String content) {
        if (null == mLoadingDialog) {
            if (TextUtils.isEmpty(content)) {
                content = mContext.getString(R.string.tip_loading);
            }
            mLoadingDialog = new LoadingDialog(mContext, content);//getString(R.string.tip_loading)
        }
        mLoadingDialog.show();
    }

    public void dismissLoading() {
        if (null != mLoadingDialog) {
            mLoadingDialog.dismiss();
            mLoadingDialog = null;
        }
    }
}
